package com.ufgov.ip.sysmanager.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.utils.Clock;

import com.ufgov.ip.sysmanager.dao.ICompanyDao;
import com.ufgov.ip.sysmanager.entity.IpCompany;
import com.ufgov.ip.util.CopyPropertiesUtil;
import com.ufgov.ip.util.ProduceCodeUtil;
import com.ufgov.ip.util.UUIDTools;
/**
 * 用户管理服务层
 * 书写readonly是说明没有特殊标识服务层只有只读事物
 * @author guangsa
 *
 */
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Service
public class IpCompanyService {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	private static Logger logger = LoggerFactory.getLogger(IpCompanyService.class);
	@Autowired
	private ICompanyDao coDao;
	

	public void setCoDao(ICompanyDao coDao) {
		this.coDao = coDao;
	}

	private Clock clock = Clock.DEFAULT;
	
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public boolean registercompany(IpCompany co) {
		try {
			
			coDao.saveCompany(co);
			
		} catch (Exception e) {
			logger.error("注册单位失败!");
			return false;
		}
		
		return true;
	}
	
	public IpCompany findIpCompanyByName(String companyName){
			
		return coDao.findByCoName(companyName);
	}
	
	
	public IpCompany findIpCompanyByNameAndparentCoId(String companyName,String pCoId){
		
		return coDao.findIpCompanyByCoNameAndParentCoId(companyName,pCoId);
	}
	
	public IpCompany findByCoCodeAndhirerId(String coCode, String hirerId) {
		// TODO 自动生成的方法存根
		return coDao.findIpCompanyByCoCodeAndHirerId(coCode, hirerId);
	}
	
	@Transactional
	public void saveIpCompanyEntity(IpCompany ipCompanyEntity, Map<String, String> resultMap) {
		// TODO 自动生成的方法存根
		Boolean checkBoolean=checkIpCompany(ipCompanyEntity,resultMap);
		if(checkBoolean){
			if (ipCompanyEntity.getCoId()==null || ipCompanyEntity.getCoId()=="") {
				ipCompanyEntity.setCoId(UUIDTools.uuidRandom());
			}
			ipCompanyEntity.setCoFullname(ipCompanyEntity.getCoName());
			ipCompanyEntity.setIsEnabled("1");
			ipCompanyEntity.setLinkman("");
			ipCompanyEntity.setDeptDetail("");
			setIpCompanyLevelNum(ipCompanyEntity);
			// coDao.save(ipCompanyEntity);
			//添加dept_detail
			setDeptDetailForIpCompany(ipCompanyEntity);
			coDao.save(ipCompanyEntity);
		}
		   
	}

	/**
	 * 设置部门详细字段 
	 * @param ipCompanyEntity
	 */
	private void setDeptDetailForIpCompany(IpCompany ipCompanyEntity) {
		IpCompany ipCompany_d = ipCompanyEntity;
		List<String> companyNameList=new ArrayList<String>();
		if(ipCompany_d.getLevelNum()!=1){
			for(int i=Integer.valueOf(ipCompany_d.getLevelNum());i>0;i--){
				if(i==1)
				  break;
				if(companyNameList.size()==0){
				  companyNameList.add(ipCompany_d.getCoName());
				}
				ipCompany_d = coDao.findByCoId(ipCompany_d.getParentCoId());
				//begin_修改增加一级部门时不拼接公司名
				if(!"1".equals(String.valueOf(ipCompany_d.getLevelNum()))){
					companyNameList.add(ipCompany_d.getCoName());
				}
				//end_修改增加一级部门时不拼接公司名
			}
		}
		Collections.reverse(companyNameList);
		StringBuffer str=new StringBuffer();
		for (String string : companyNameList) {
			str.append(string);
		}
		ipCompanyEntity.setDeptDetail(str.toString());
	}
	
	/**
	 * 更新部门
	 * @param ipCompanyEntity
	 * @param resultMap
	 */
	@Transactional
	public void updateIpCompanyEntity(IpCompany ipCompanyEntity, Map<String, String> resultMap) {
		
		Boolean checkBoolean = checkIpCompany(ipCompanyEntity, resultMap);
		if(checkBoolean){
			IpCompany findByCoId = coDao.findByCoId(ipCompanyEntity.getCoId());
			// 取原值 
			ipCompanyEntity.setDispOrder(findByCoId.getDispOrder());
			CopyPropertiesUtil.copyProperty(findByCoId, ipCompanyEntity);
			findByCoId.setCoFullname(findByCoId.getCoName());
			setIpCompanyLevelNum(findByCoId);
			setDeptDetailForIpCompany(findByCoId);
			coDao.save(findByCoId);
		}
	}
	
	
	/**
	 * 设置部门级别
	 * @param ipCompanyEntity
	 */
	private void setIpCompanyLevelNum(IpCompany ipCompanyEntity) {
		if(ipCompanyEntity.getParentCoId()!=null){
			String parentCoId=ipCompanyEntity.getParentCoId();
			IpCompany ipCompanyByParent= findIpCompanyByCoId(parentCoId);
			if(ipCompanyByParent!=null){
//				ipCompanyEntity.setLevelNum(String.valueOf((Integer.valueOf(ipCompanyByParent.getLevelNum())+1)));
				ipCompanyEntity.setLevelNum(ipCompanyByParent.getLevelNum()+1);
			}
		}
	}
	
	/**
	 * 验证
	 * @param entity
	 * @param resultMap
	 * @return
	 */
	private Boolean checkIpCompany(IpCompany ipCompanyEntity, Map<String, String> resultMap) {
		IpCompany ipCompany= findIpCompanyByNameAndparentCoId(ipCompanyEntity.getCoName(),ipCompanyEntity.getParentCoId());
		if(ipCompany!=null){
			// 更新 
			if(null!=ipCompanyEntity.getCoId()&&!("").equals(ipCompanyEntity.getCoId())){
				if(!ipCompanyEntity.getCoId().equals(ipCompany.getCoId())){
					 getErrorMsg(resultMap,"该部门名称已存在！");
					 return false;
				}
			}else{// 新增直接返回错误信息 
			  getErrorMsg(resultMap,"该部门名称已存在！");
			  return false;
			}
		}
		// 判断部门编码 
		IpCompany ipCompanyByCoCode =findByCoCodeAndhirerId(ipCompanyEntity.getCoCode(),ipCompanyEntity.getHirerId());
		if(ipCompanyByCoCode!=null){
			// 更新 
			if(null!=ipCompanyEntity.getCoId()&&!("").equals(ipCompanyEntity.getCoId())){
				if(!ipCompanyEntity.getCoId().equals(ipCompanyByCoCode.getCoId())){
					 getErrorMsg(resultMap,"该部门编码已存在！");
					 return false;
				}
			}else{// 新增直接返回错误信息 
			  getErrorMsg(resultMap,"该部门编码已存在！");
			  return false;
			}
		}
		if(null!=ipCompanyEntity.getParentCoId()&&!("").equals(ipCompanyEntity.getParentCoId())){
			IpCompany parentMenu =findIpCompanyByCoId(ipCompanyEntity.getParentCoId());
			if(parentMenu==null){
				getErrorMsg(resultMap,"父菜单已不存在，请确认！");
				return false;
			}
		}
		return true;
		
	}
	
	

	private Boolean checkIpCompanyForUpdate(IpCompany ipCompanyEntity, Map<String, String> resultMap) {
		
		if(null!=ipCompanyEntity.getParentCoId()&&!("").equals(ipCompanyEntity.getParentCoId())){
			IpCompany parentMenu =findIpCompanyByCoId(ipCompanyEntity.getParentCoId());
			if(parentMenu==null){
				getErrorMsg(resultMap,"父菜单已不存在，请确认！");
				return false;
			}
		}
		return true;
		
	}
	
	
	/**
	 * 通过部门ID查询部门信息 
	 * @param coId 部门ID
	 * @return
	 */
	private IpCompany findIpCompanyByCoId(String coId) {
		return coDao.findByCoId(coId);
	}
	
	/**
	 * 获得当前部门的所有子部门
	 * @param parentCoId
	 * @return
	 */
	public List<IpCompany> findCompanyByParentCoId(String parentCoId){
		
		List<IpCompany> ipCompanies= coDao.findCompanyByParentCoId(parentCoId);
		List<IpCompany> ipCompanyList =new ArrayList<IpCompany>();
		int order = 1;
		// 部门顺序显示  从1开始1、2、3、4、....
//		for (IpCompany ipCompany : ipCompanies) {
//			ipCompany.setDispOrder(order+"");
//			ipCompanyList.add(ipCompany);
//			order++;
//		}
		return ipCompanies;
	}
	

	/**
	 * 错误信息 
	 * @param resultMap
	 * @param reason
	 */
	private void getErrorMsg(Map<String, String> resultMap,String reason) {
		resultMap.put("result", "fail");
		resultMap.put("reason", reason);
	}

	public List<IpCompany> getCompanyPage(Map<String, Object> searchParams,
			Sort sort) {
		// TODO 自动生成的方法存根
		 Specification<IpCompany> spec = buildSpecification(searchParams);
		 return coDao.findAll(spec, sort);
	}  
	/**
     * 创建动态查询条件组合.
     */
    public Specification<IpCompany> buildSpecification(Map<String, Object> searchParams) {
        Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
        Specification<IpCompany> spec = DynamicSpecifications.bySearchFilter(filters.values(), IpCompany.class);
        return spec;
    }

	public IpCompany findByCoId(String coId) {
		// TODO 自动生成的方法存根
		return coDao.findByCoId(coId);
	}

	@Transactional
	public void updateCompanyBycoId(String coId, String parentCoId) {
		// TODO 自动生成的方法存根
			coDao.updateCompanyBycoId(coId,parentCoId);
	}
    
	@Transactional
	public void delete(IpCompany findByCoId) {
		// TODO 自动生成的方法存根
		coDao.delete(findByCoId);
		
	}

	public List<IpCompany> findCompanyByDeptDetailLike(String deptDetail,String hirerId) {
		return coDao.findCompanyByDeptDetailLike(deptDetail,hirerId);
	}
	
	public List<IpCompany> findAll() {
		return (List<IpCompany>) coDao.findAll();
	}

	public List<IpCompany> findCompanyByHirerId(String hirerId) {
		// TODO 自动生成的方法存根
		return coDao.findCompanyByHirerId(hirerId);
	}
	
	
}
